package com.qunar.comet.demo;

import java.io.IOException;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/websocket")
public class WebSocketTest {

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        System.out.println("Received:" + message);
        
        session.getBasicRemote().sendText("This is the first server message");
        
        int sentMessage = 0;
        while (sentMessage < 3) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            session.getBasicRemote().sendText("This is an intermediate server message. Count:" + sentMessage);
            sentMessage++;
        }
        session.getBasicRemote().sendText("This is the last server message");
        
    }
    
    @OnOpen
    public void onOpen() {
        System.out.println("Client connected");
    }
    
    @OnClose
    public void onClose() {
        System.out.println("Client close");
    }
    
    @OnError
    public void onError(Throwable t) {
        System.out.println("WebSocketTest.onError() " + t.getMessage());
    }
}
